package com.o2o.intercepitor;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.StrutsStatics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.o2o.content.CookieContent;
import com.o2o.content.SessionContent;
import com.o2o.model.user.User;
import com.o2o.service.UserService;
import com.o2o.util.CookieUtil;
import com.o2o.util.CryptUtil;
import com.o2o.util.MD5Util;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class AutoLoginInterceptior implements Interceptor {


	/**
	 * 
	 */
	private static final long serialVersionUID = -8857070309236483721L;
	
	@Resource
	UserService userService;

	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Override
	public void destroy() {
		logger.info("********AutoLoginIntercepitor destroy**********");
	}

	@Override
	public void init() {
		logger.info("*********AutoLoginIntercepitor init************");
	}
	
	@Override
	public String intercept(ActionInvocation invoc) throws Exception {
		HttpServletRequest request= (HttpServletRequest)  invoc.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);  
		Map<String, Object> session = invoc.getInvocationContext().getSession();
		if(session.get(SessionContent.NORMAL_USER_SESSION) == null){
			try {
				String accountString = CookieUtil.findCookie(CookieContent.AUTO_LOGIN_ACCOUNT, request);
				String decrypt3des = null;
				String email = "";
				if(accountString != null && !accountString.equals("")){
					String[] split = accountString.split(",");
					String encrypt = split[0]; 
					email = split[1];
					String md5Key =  MD5Util.getMD5String("_How can you find this key_"+email);
					decrypt3des = CryptUtil.Decrypt3DES(encrypt, md5Key);
				}
				if(decrypt3des != null){
					User user = userService.getUserByEmailAccount(email);
					if(user != null && MD5Util.getMD5String(decrypt3des).equals(user.getPasswd())){
						//自动登陆成功
						session.put(SessionContent.NORMAL_USER_SESSION, user);
						logger.info("*********auto  login intercepter success,login email:"+email+"*******");
					}
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return invoc.invoke();
	}

}
